import os
import cv2

from parking_detect.load_json import load_config


class ShowConfig(object):
    def __init__(self, mask_path, config_path):
        self.img = self.read_image(mask_path)
        self.data = self.load_config(config_path)

    def read_image(self, path):
        if not os.path.exists(path):
            raise FileNotFoundError("{} is not found".format(path))
        return cv2.imread(path)

    def show_config(self, results=None):
        # 遍历配置文件中的每个区域
        for i in self.data:
            # 画出矩形框和车位名字
            cv2.rectangle(self.img, (int(i.x1), int(i.y1)), (int(i.x2), int(i.y2)), (255, 0, 0), 2)
            cv2.putText(self.img, i.name, (int(i.x1 + i.x2) // 2, int(i.y1) + 10), cv2.FONT_HERSHEY_SIMPLEX, 1,
                        (0, 255, 255), 2)
        # 传入结果的是话, 则画出结果
        if results:
            self.draw_results(results)

        self.img = cv2.resize(self.img, (0, 0), fx=0.5, fy=0.5)

        cv2.imshow("parking", self.img)
        cv2.imwrite(r"C:\Users\ruiyangz\Desktop\yolov5-pytorch-main\img\generated.jpg", self.img)
        if cv2.waitKey(0) & 0xFF == ord("q"):
            cv2.destroyAllWindows()

    def load_config(self, config_path):
        return load_config(config_path)

    def draw_results(self, results):
        """ 展示配置文件何结果(用于调试) """
        for _, x1, y1, x2, y2 in results:
            cv2.rectangle(self.img, (x1, y1), (x2, y2), (0, 255, 0), 2)


if __name__ == '__main__':
    src = r"C:\Users\ruiyangz\Desktop\yolov5-pytorch-main\img\demo.jpg"
    config = r"C:\Users\ruiyangz\Desktop\yolov5-pytorch-main\parking_detect\parking.json"
    test = ShowConfig(src, config)
    test.show_config()
